/* eslint-disable no-debugger */
import React, { useState, useRef, CSSProperties, useEffect } from "react";
import loginPath from "@/assets/login.svg";
import { Col, Row, Space, Typography, Flex, Segmented, message, theme, QRCode } from "antd";
import styles from "./styles/login.module.less";
import logoPath from "@/assets/logo.svg";
import { LoginForm, ProFormCaptcha, ProFormCheckbox, ProFormText } from "@ant-design/pro-components";
import { LeftOutlined, LockOutlined, MobileOutlined, SecurityScanOutlined, UserOutlined } from "@ant-design/icons";
import IconFont from "@/components/IconFont";
import LoginActions from "./components/LoginActions";
import { useNavigate } from "react-router-dom";
import useSize from "@/hooks/useSize";
import { login, getCaptcha as requestCaptcha } from "@/services/api/Login";
import useToken from "@/hooks/useToken";
import { useDispatch } from "@/store";
import { getUserInfo } from "@/store/modules/global";
import LangSwitch from "./components/LangSwitch";
import { loginTypeOption, phoneRules } from "./constant";
import { getQueryObject, getRoutePath } from "@/utils";
const MobileForm = () => {
	return (
		<>
			<ProFormText
				fieldProps={{
					size: "large",
					prefix: <MobileOutlined />
				}}
				name="mobile"
				placeholder={"手机号"}
				rules={phoneRules}
			/>
			<ProFormCaptcha
				fieldProps={{
					size: "large",
					prefix: <LockOutlined />
				}}
				captchaProps={{
					size: "large"
				}}
				placeholder={"请输入验证码"}
				captchaTextRender={(timing, count) => {
					if (timing) {
						return `${count} 获取验证码`;
					}
					return "获取验证码";
				}}
				name="captcha"
				rules={[
					{
						required: true,
						message: "请输入验证码！"
					}
				]}
				onGetCaptcha={async phone => {
					message.success("获取验证码成功！验证码为：1234");
				}}
			/>
		</>
	);
};
const AccountForm: React.FC<{ enableCaptcha?: boolean; captchaBase64?: string; onGetCaptcha?: () => void }> = ({
	enableCaptcha = false,
	captchaBase64 = "",
	onGetCaptcha = () => {}
}) => {
	return (
		<>
			<ProFormText
				name="username"
				fieldProps={{
					size: "large",
					prefix: <UserOutlined />
				}}
				placeholder="用户名"
				rules={[
					{
						required: true,
						message: "请输入用户名"
					}
				]}
			/>
			<ProFormText.Password
				name="password"
				fieldProps={{
					size: "large",
					prefix: <LockOutlined />
				}}
				placeholder="密码"
				rules={[
					{
						required: true,
						message: "请输入密码！"
					}
				]}
			/>
			{enableCaptcha && (
				<div className={styles.captcha}>
					<ProFormText
						name="code"
						fieldProps={{
							size: "large",
							prefix: <SecurityScanOutlined className={styles.prefixIcon} />
						}}
						placeholder="验证码"
						rules={[
							{
								required: true,
								message: "请输入验证码"
							}
						]}
					/>
					<img style={{ cursor: "pointer" }} onClick={onGetCaptcha} src={`data:image/png;base64,${captchaBase64}`} />
				</div>
			)}
		</>
	);
};
const Login = () => {
	const {
		token: { colorPrimary }
	} = theme.useToken();
	const dispatch = useDispatch();
	const { pushToken } = useToken();
	const loginPageRef = useRef<HTMLDivElement>(null);
	const navigator = useNavigate();
	const [type, setType] = useState<string>("account");
	const [enableCaptcha, setEnableCaptcha] = useState<boolean>(false);
	const [captchaBase64, setCaptchaBase64] = useState<any>("");
	const [captchaUUID, setCaptchaUUID] = useState<any>("");
	const [captchaType, setCaptchaType] = useState<any>("");
	const { width } = useSize(loginPageRef);
	const [actionType, setActionType] = useState<string>("");
	const query = getQueryObject();
	const redirectUrl = decodeURIComponent(query.redirectUrl || "");

	const handleSubmit = async (values: any) => {
		// 登录
		return login({
			uuid: captchaUUID,
			...values
		})
			.then(async res => {
				pushToken(res?.data["access_token"]);
				// @ts-ignore
				await dispatch(getUserInfo());
				setTimeout(() => {
					debugger;
					// @ts-ignore
					if (redirectUrl) {
						const path = getRoutePath(redirectUrl, true);
						navigator(path);
					} else {
						navigator("/home");
					}
					return Promise.resolve();
				}, 300);
			})
			.catch(() => {
				getCaptcha();
				return Promise.resolve();
			});
	};
	const handleActionClick = (type: string) => {
		setActionType(type);
	};
	const handleGoAccount = () => {
		setActionType("");
	};
	//请求验证码
	const getCaptcha = () => {
		requestCaptcha().then(data => {
			setEnableCaptcha(data.captchaEnabled);
			setCaptchaBase64(data.img);
			setCaptchaUUID(data.uuid);
			setCaptchaType(data?.captchaType);
		});
	};
	useEffect(() => {
		getCaptcha();
	}, []);
	return (
		<React.Fragment>
			<Row ref={loginPageRef}>
				{width > 575 && (
					<Col className={styles.leftContainer} span={13}>
						<div style={{ height: "60px", padding: "50px 0px 0px 30px" }}>
							<Space align="center">
								<img width={30} src={logoPath} />
								<Typography.Title style={{ marginBottom: "0" }} level={4}>
									内部开发平台
								</Typography.Title>
							</Space>
						</div>
						<div className="flx-center" style={{ height: "calc(100vh - 110px)" }}>
							<img width={600} src={loginPath} />
						</div>
					</Col>
				)}

				<Col span={width < 576 ? 24 : 11} className={styles.rightContainer}>
					<div className={styles.header} style={{ justifyContent: actionType === "" ? "flex-end" : "space-between" }}>
						{actionType !== "" && (
							<Space style={{ cursor: "pointer" }} onClick={handleGoAccount}>
								<LeftOutlined style={{ color: colorPrimary }} />
								<Typography>账号登录</Typography>
							</Space>
						)}
						<LangSwitch />
					</div>
					<div className={styles.loginBox}>
						<div className={styles.customLoginForm}>
							{actionType === "" && (
								<LoginForm
									contentStyle={{
										minWidth: "360px",
										maxWidth: "75vw"
									}}
									actions={<LoginActions onClick={handleActionClick} />}
									title={"欢迎回来!"}
									subTitle={
										<Space size={2}>
											<div>还没有账号?</div>
											<Typography.Link>创建新账号</Typography.Link>
										</Space>
									}
									initialValues={{
										autoLogin: true,
										username: "admin",
										password: "admin123"
									}}
									onFinish={handleSubmit}
								>
									<Segmented
										defaultValue={type}
										style={{ margin: "16px 0px 16px 0px" }}
										onChange={(value: any) => setType(value)}
										size="large"
										options={loginTypeOption}
									/>
									{type === "account" ? (
										<AccountForm onGetCaptcha={() => getCaptcha()} enableCaptcha={enableCaptcha} captchaBase64={captchaBase64} />
									) : (
										<MobileForm />
									)}

									<Flex style={{ marginBottom: "10px" }} justify="space-between" align="center">
										<ProFormCheckbox noStyle name="autoLogin">
											下次自动登录
										</ProFormCheckbox>
										<Typography.Link>忘记密码?</Typography.Link>
									</Flex>
								</LoginForm>
							)}
							{actionType === "wechat" && (
								<>
									<Flex align="center" vertical={true}>
										<QRCode
											size={280}
											errorLevel="L"
											value="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
										/>
										<Typography.Title level={4}>微信登录</Typography.Title>
										<Typography.Text type="secondary">使用手机微信扫一扫登录</Typography.Text>
									</Flex>
								</>
							)}
						</div>
					</div>
				</Col>
			</Row>
		</React.Fragment>
	);
};
export default Login;
